package com.ikun.common.utils;


import com.alibaba.fastjson2.JSON;
import com.ikun.common.result.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author ximeng
 * @title: ResponseUtils
 * @projectName iot-fy-2301-parent
 * @description: TODO
 * @date 2023/10/18  9:19
 */
public class ResponseUtils {

    private static Logger logger= LoggerFactory.getLogger(ResponseUtils.class);

    /**
     * 向客户端写入数据
     *
     * @param req
     * @param resp
     * @param r
     */
    public static void sendResponse(HttpServletRequest req ,HttpServletResponse resp, Result result) {
        String jsonString = JSON.toJSONString(result);
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = null;
        try {
            writer = resp.getWriter();
            writer.write(jsonString);
            writer.flush();
            writer.close();
        } catch (IOException e) {
             logger.error("向客户端写回数据失败");
            throw new RuntimeException(e);
        }

    }

    /**
     *
     * @param resp
     * @param r
     */
    public static void sendResponse(HttpServletResponse resp, Result result) {
        String jsonString = JSON.toJSONString(result);
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = null;
        try {
            writer = resp.getWriter();
            writer.write(jsonString);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            logger.error("向客户端写回数据失败");
            throw new RuntimeException(e);
        }

    }

}
